import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import org.gearman.client.GearmanClientImpl;
import org.gearman.client.GearmanJob;
import org.gearman.client.GearmanJobImpl;
import org.gearman.client.GearmanJobResult;
import org.gearman.common.GearmanJobServerConnection;
import org.gearman.common.GearmanNIOJobServerConnection;
import org.gearman.util.ByteUtils;


public class GearClient {
	private final GearmanClientImpl client;

    public GearClient(String host, int port) throws IOException {
        GearmanJobServerConnection connection =
                new GearmanNIOJobServerConnection(host, port);
        client = new GearmanClientImpl();
        
        client.addJobServer(connection);
    }

    public String echo(String input) throws IOException {
        byte[] data = ByteUtils.toUTF8Bytes(input);
        byte[] respBytes = client.echo(data);        
        return ByteUtils.fromUTF8Bytes(respBytes);
    }

    public void shutdown() throws IllegalStateException {
        if (client == null) {
            throw new IllegalStateException("No client to shutdown");
        }
        client.shutdown();
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
    	 String host = GearConstants.GEARSERVER_HOST; 
         int port = GearConstants.GEARSERVER_PORT;
         
        String payload = "hello!";
        
        for (String arg : args) {
            if (arg.startsWith("-h")) {
                host = arg.substring(2);
            } else if (arg.startsWith("-p")) {
                port = Integer.parseInt(arg.substring(2));
            }
        }

        try {
    		GearClient ec = new GearClient(host,port);
        	// Create a job to submit to server
        	GearmanJob job = GearmanJobImpl.createJob(GearConstants.FunctionName.WORKERFUNCTIONEX.getName(), payload.getBytes(), 1 + "");
        	Future<GearmanJobResult> _result = ec.client.submit(job);
        	GearmanJobResult gearmanJobResult = _result.get();
        	String str = new String(gearmanJobResult.getResults()); 
        	ec.shutdown();
        	
        	System.out.println("CLIENT SHUTDOWN");
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}
